import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/views/report/model/leads_source_report.dart';
import 'package:syncfusion_flutter_charts/charts.dart';


import '../../res/w_colors.dart';
import '../../res/w_dimens.dart';
import '../../widget/custom_search.dart';
import '../../widget/sort_content.dart';
import '../../widget/w_line.dart';
import '../../widget/w_popup_window.dart';
import '../../widget/w_text.dart';
import 'model/chart_data.dart';

class LeadsSourceReportPage extends StatefulWidget {
  const LeadsSourceReportPage({super.key});

  @override
  BaseState<LeadsSourceReportPage> createState() =>
      LeadsSourceReportPageState();
}

class LeadsSourceReportPageState extends BaseState<LeadsSourceReportPage> {
  Map sortParams = {};

  Map<String, dynamic> queryParams = {};
  List<LeadsSourceReport> dataList = [];

  Future<Null> _refresh() async {
    showLoading();
    fetchDataList();
  }

  @override
  void initState() {
    super.initState();
    fetchDataList();
  }

  void fetchDataList() {
    HttpUtils()
        .get(Api.getClueSourceReport, queryParams: queryParams)
        .then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data ?? [];
          List<LeadsSourceReport> list =
              data.map((item) => LeadsSourceReport.fromJson(item)).toList();
          setState(() {
            dataList = list;
          });
        }
      }
    });
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "线索来源渠道分布报表",
      rightWidget: GestureDetector(
        onTap: () {
          WPopupWindow.showSort(
              context: context,
              sortType: SortType.LEADS_SOURCE_REPORT,
              sortParams: sortParams,
              onSelected: (Map params) {
                sortParams = params;
                params.forEach((key, value) {
                  queryParams[key] = value;
                  if (queryParams.containsKey(key) && value == null) {
                    queryParams.remove(key);
                  }
                });
                showLoading();
                fetchDataList();
              });
        },
        child: Padding(
          padding: EdgeInsets.only(right: 10.px),
          child: WText(
            "筛选",
            style: TextStyle(
              color: WColors.primaryColor,
              fontSize: 14.px,
            ),
          ),
        ),
      ),
      child: Column(
        children: [
          Expanded(
            child: RefreshIndicator(
                onRefresh: _refresh,
                child: ListView.builder(
                  padding: EdgeInsets.only(top: 10.px),
                  itemBuilder: _listItem,
                  itemCount: dataList.length,
                )),
          ),
        ],
      ),
    );
  }

  Widget _listItem(context, index) {
    LeadsSourceReport item = dataList[index];
    List<ChartData>? data = item.itemList
        ?.map((it) => ChartData(it.itemName, it.clueNum, it.clueRate))
        .toList();

    return Container(
        decoration: BoxDecoration(boxShadow: [
          BoxShadow(
              color: WColors.CDFEFFB,
              offset: const Offset(0, 1),
              blurRadius: 3.px)
        ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
        margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
        padding: EdgeInsets.only(bottom: 10.px),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 10.px),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  WLine(
                    height: 16.px,
                    width: 4.px,
                    color: WColors.primaryColor,
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10.px),
                      child: WText(
                        item.title ?? "",
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: WDimens.tsLarge,
                            color: WColors.mainTextColor,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(right: 20.px),
                    child: WText(
                      "店面数量: ${item.shopNum ?? "-"}",
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: WDimens.tsLarge,
                        color: WColors.mainTextColor,
                      ),
                    ),
                  ),
                ],
              ),

              SizedBox(
                height: 500.px,
                child: SfCartesianChart(
                    primaryXAxis: const CategoryAxis(
                      majorGridLines: MajorGridLines(width: 0),
                      isInversed: true,
                    ),
                    primaryYAxis: const NumericAxis(
                      isVisible: false,
                    ),
                    series: <CartesianSeries<ChartData, String>>[
                      BarSeries<ChartData, String>(
                          dataSource: data,
                          dataLabelMapper: (ChartData data, _) =>
                              "${data.y} / ${data.rate}%",
                          dataLabelSettings: DataLabelSettings(isVisible: true),
                          xValueMapper: (ChartData data, _) => data.x,
                          yValueMapper: (ChartData data, _) => data.y,
                          color: WColors.primaryColor)
                    ]),
              )
            ]));
  }
}
